package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.ContractItem;
import com.neusoft.neuiotms.dcam.fixed.model.QContractItem;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedContractItemRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedContractItemRepositoryImpl extends AbstractRepository
        implements CustomizedContractItemRepository {

    @Override
    public List<ContractItem> index(final Searchable searchable) {
        final QContractItem qContractItem = QContractItem.contractItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ContractItem> query = this.query().selectFrom(qContractItem);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<ContractItem> search(final Pageable pageable, final Searchable searchable) {
        final QContractItem qContractItem = QContractItem.contractItem;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<ContractItem> query = this.query().selectFrom(qContractItem);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return ContractItem.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QContractItem qContractItem = QContractItem.contractItem;

        where.and(super.equalsStr(qContractItem.contract.code, searchable, "code"));
        where.and(super.equalsLong(qContractItem.contract.id, searchable, "contractId"));
        where.and(super.containsStr(qContractItem.description, searchable, "description"));
        return where;
    }

}
